package middleware

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	rdb "tieup/pkg/redis"
)

func TokenAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从Header获取完整令牌
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"error": "缺失认证令牌",
			})
			return
		}

		// 提取令牌部分 (移除Bearer前缀)
		token := strings.TrimPrefix(authHeader, "Bearer ")
		if token == authHeader {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
				"error": "令牌格式错误，需使用Bearer方案",
			})
			return
		}

		// 解析令牌
		parts := strings.Split(token, ":")
		if len(parts) != 4 {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
				"error": "令牌格式无效，应为 user_id:biz_code:token:round_char",
			})
			return
		}

		userID, bizCode, roundChar, tokenValue := parts[0], parts[1], parts[2], parts[3]

		// 构造Redis key
		redisKey := fmt.Sprintf("share:%s_%s_%s", userID, bizCode, roundChar)

		// 从Redis获取存储的令牌值
		storedToken, err := rdb.Client.Get(context.Background(), redisKey).Result()
		if errors.Is(err, redis.Nil) {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"error": "令牌已过期或不存在",
			})
			return
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
				"error": "服务器内部错误",
			})
			return
		}

		// 验证令牌值
		if storedToken != tokenValue {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"error": "令牌验证失败",
			})
			return
		}

		// 验证成功后删除Redis中的令牌（一次性使用）测试时注释掉
		// rdb.Client.Del(context.Background(), redisKey)

		// 将用户ID和业务码存入上下文
		c.Set("user_id", userID)
		c.Set("biz_code", bizCode)
		c.Next()
	}
}
